<template>
	<div style="padding-bottom: 100px;">
		<view style="background-color: #ffffff;margin: 10px;border-radius: 12px;padding: 15px;">
			<uni-forms ref="form" :modelValue="formData"  :rules="rules" labelPosition="top" labelWidth="90px">
				<view style="display: flex;">
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="货物名称" style="width: 90%;" name="goodsName" required>
							<uni-combox v-if="formData.pickupOrderNo===undefined"  @input="selectGoods" :candidates="goodsList" placeholder="货物名称"
								v-model="formData.goodsName"></uni-combox>
							<uni-easyinput v-else :disabled="true" type="text" v-model="formData.goodsName" placeholder="货物名称" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="货物类型" style="width: 90%;" name="goodsType" required>
							<uni-data-select :disabled="true" v-model="formData.goodsType" :localdata="goodsType"
								style="background-color: white;" />
						</uni-forms-item>
					</view>
					<!-- <view style="flex: 1;">
						<uni-forms-item label="货主单号" style="width: 90%;">
							<uni-easyinput type="text" v-model="formData.shipperId" placeholder="货主单号" />
						</uni-forms-item>
					</view> -->
				</view>
				<view style="display: flex;">
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="包装类型" style="width: 90%;" name="packingType" required>
							<uni-data-select :disabled="isPackingService" v-model="formData.packingType" :localdata="packingType"
								style="background-color: white;" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="包装服务" style="width: 90%;" name="packingService" required>
							<uni-data-select :clear="false" @change="changePackingService" v-model="formData.packingService" :localdata="packingService"
								style="background-color: white;" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;">
						<uni-forms-item label="计费方式" style="width: 90%;" name="feeMode" required>
							<uni-data-select @change="selectFeeMode" v-model="formData.feeMode" :localdata="feeMode"
								style="background-color: white;" />
						</uni-forms-item>
					</view>
				</view>
				<view style="display: flex;">
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="数量" style="width: 90%;" name="num">
							<uni-easyinput :disabled="formData.pickupOrderNo!==undefined" @input="inputNum" type="number" v-model="formData.num" placeholder="数量" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="重量(吨)" style="width: 90%;" name="weight" required>
							<uni-easyinput :disabled="formData.pickupOrderNo!==undefined" @input="inputWeight" type="digit" v-model="formData.weight" placeholder="重量(吨)" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;">
						<uni-forms-item label="体积(立方)" style="width: 90%;" name="bulk">
							<uni-easyinput :disabled="formData.pickupOrderNo!==undefined" @input="inputBulk" type="digit" v-model="formData.bulk" placeholder="体积(立方)" />
						</uni-forms-item>
					</view>
				</view>
				<view style="display: flex;">
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="包装费" style="width: 90%;" name="packingFee">
							<uni-easyinput @input="limitInput($event,'packingFee')" type="digit" v-model="formData.packingFee" placeholder="包装费" />
						</uni-forms-item>
					</view>
					<view style="flex: 1;">
						<uni-forms-item label="运费小计(元)" style="width: 90%;" name="carriageFee" required>
							<uni-easyinput @input="limitInput($event,'carriageFee',3)" type="digit" v-model="formData.carriageFee" placeholder="运费小计(元)" />
						</uni-forms-item>
					</view>
				</view>
				<view v-if="formData.pickupOrderNo" style="display: flex;">
					<view style="flex: 1;margin-right: 5px;">
						<uni-forms-item label="提货单号" style="width: 90%;">
							<text>{{formData.pickupOrderNo}}</text>
						</uni-forms-item>
					</view>
				</view>
				<uni-forms-item label="相关附件" name="file">
					<myfilepicker :limit="'3'" :imageStyles="imageStyles" :fileIdString="formData.otherFiles" :fileExtname="'png,jpg,jpeg'" :fileMediatype="'image'"  @transFileIdString="getFileIdString"
							:title="'*点击可上传物品附件，支持png/jpg/jpeg，最多可上传3个附件*'"></myfilepicker>
					</uni-forms-item>
				</uni-forms-item>
			</uni-forms>
		</view>
		<view
			style="background-color: #ffffff;z-index: 2;height: 70px;width:100%;position: fixed;bottom: 0;display: flex;box-shadow: 0px 0px 11px rgba(0, 0, 0, 0.1);">
			<view
				style="display: flex;align-items: center;width: 50%;height: 60px;justify-content: center;">
				<view @click="cancelSubmit()" hover-class="buttonHover"
					style="height: 35px;background-color: #ffffff;border:1px solid #bf5f09;color: #bf5f09;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
					取消</view>
			</view>
			<view
				style="display: flex;align-items: center;width: 50%;height: 60px;justify-content: center;">
				<view @click="submit()" hover-class="buttonHover"
					style="height: 35px;background-color: #bf5f09;color: #ffffff;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
					确定</view>
			</view>
		</view>
	</div>
</template>

<script>
	import {pricePlanList,getPlanCalcAmountFee,getPlanCalcWeigthMultiMileFee} from '@/api/system/planPrice.js'
	import {getSourceList} from '@/api/system/source.js'
	import {getDicts} from '@/api/system/dict.js'
	import myfilepicker from '@/components/uploadFile/uploadFile.vue'
	
	import Config from '@/uni_modules/Lyn4ever-gaodeRoutePlanning/lib/config.js';
	
	export default {
		components: {
			myfilepicker
		},
		data() {
			return {
				formData:{
					goodsName:'',
					goodsType:'',
					shipperId:'', //货主单号暂无
					packingType:'',
					packingService:'0',
					feeMode:'',
					num:'',
					weight:'',
					bulk:'',
					packingFee:'',
					carriageFee:'',
					otherFiles:''
				},
				// 校验规则
				rules: {
					goodsName: {
						rules: [{
								required: true,
								errorMessage: '请输入货物名称',
							}
						]
					},
					goodsType: {
						rules: [{
							required: true,
							errorMessage: '请选择货物类型',
						}]
					},
					packingType: {
						rules: [{
							required: true,
							errorMessage: '请选择包装类型',
						}]
					},
					packingService: {
						rules: [{
							required: true,
							errorMessage: '请选择包装服务',
						}]
					},
					feeMode: {
						rules: [{
							required: true,
							errorMessage: '请选择计费方式',
						}]
					},
					// num: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入数量(件)',
					// 	}]
					// },
					weight: {
						rules: [{
							required: true,
							errorMessage: '请输入重量(吨)',
						}]
					},
					// bulk: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入体积(立方)',
					// 	}]
					// },
					carriageFee: {
						rules: [{
							required: true,
							errorMessage: '请输入运费小计(元)',
						}]
					}
				},
				imageStyles: {
					width: '100px',
					height: 100,
					border: {
						radius: '4px'
					}
				},
				//货物列表
				goodsList:[],
				//所有货物对象列表
				goodsObject:[],
				//下拉框->货物类型
				goodsType: [],
				//下拉框->包装类型
				packingType: [],
				//是否包装置灰
				isPackingService:true,
				//下拉框->包装服务
				packingService: [
					{
						value:'0',
						text:'否，外部包装'
					},
					{
						value:'1',
						text:'是，包装服务'
					}
				],
				//下拉框->计费方式
				feeMode:[],
				index:'',
				//节流函数标志
				statu:true,
				planId:'',
				
				//里程
				distance:0,
				//传过来的地址信息
				district:{}
			}
		},
		onLoad(e) {
			if(e.goodsDetails&&e.index)
			{
				//设置顶部导航栏标题
				uni.setNavigationBarTitle({
					title: '编辑物品'
				})
				this.index=e.index
				this.formData=JSON.parse(e.goodsDetails)
				this.district=JSON.parse(e.district)
				this.changePackingService()
				//计算里程
				this.getLanLatInit()
				//获取当前计费方式
				this.getNowPricePlanList()
				
				//this.limitInput(newVal,'packingFee')
			}
			else if(e.district)
			{
				this.district=JSON.parse(e.district)
				//计算里程
				this.getLanLatInit()
				//获取默认计费方式
				pricePlanList({}).then(res => {
				    const find = res.rows.find(item => item.status === '0')
				    if (!find) return
				    //this.isOpen = find.feeMode
					this.formData.feeMode=find.feeMode
					this.planId=find.id
				})
			}
		
		},
		created() {
			//获取货物列表下拉检索
			getSourceList({pageNum:1,pageSize:1000}).then(res=>{
				this.goodsList=res.rows.map(item=>{
					return item.goodsName
				})
				this.goodsObject=res.rows;
			})
			
			//获取货物类型下拉框
			getDicts('goods_type').then(res=>{
				this.goodsType=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取包装类型下拉框
			getDicts('packing_type').then(res=>{
				this.packingType=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			//获取计费方式下拉框
			getDicts('price_method').then(res=>{
				this.feeMode=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
		},
		methods: {
			async getLanLatInit(){
				let startPoi=await this.getLanLat(this.district.shipDistrictName,this.district.shipAddress)
				let endPoi=await this.getLanLat(this.district.deliveryDistrictName,this.district.deliveryAddress)
				this.distance=await this.calculateMileage(startPoi,endPoi)
			},
			//根据名称获取经纬度
			getLanLat(districtName,Address){	
				return new Promise((resolve, reject) => {
					uni.request({
						 url: 'https://restapi.amap.com/v3/geocode/geo?parameters', 
						method:'GET',
						 data: {
							key: Config.GAODE_WEB_KEY,
							address:districtName+Address
						 },
						success: (res) => {
							resolve(res.data.geocodes[0].location)
						}
					}) 
				})
			},
			//计算里程
			calculateMileage(startPoi,endPoi){
				return new Promise((resolve, reject) => {
					uni.request({
						 url: 'https://restapi.amap.com/v3/direction/driving?parameters', 
						method:'GET',
						 data: {
							key: Config.GAODE_WEB_KEY,
							origin:startPoi,
							destination:endPoi
						 },
						success: (res) => {
							resolve((res.data.route.paths[0].distance)/1000)
						}
					}) 
				})
			},
			//计算单个运费的小计(计算体积、重量、数量费用费用)
			calculateCarriageFee(planId)
			{
				if(this.formData.feeMode==='weight')  //如果为重量
				{
					getPlanCalcAmountFee(planId,this.formData.weight||0).then(res=>{
						this.formData['carriageFee']=res.data
					})	
				}
				else if(this.formData.feeMode==='volume') //如果为体积
				{
					getPlanCalcAmountFee(planId,this.formData.bulk||0).then(res=>{
						this.formData['carriageFee']=res.data
					})	
				}
				else if(this.formData.feeMode==='weightMultiMileage') //如果为重量*里程
				{
					getPlanCalcWeigthMultiMileFee(planId,this.distance,this.formData.weight||0).then(res=>{
						this.formData['carriageFee']=res.data
					})	
				}
				// else if(this.formData.feeMode==='volume') //如果为数量
				// {
				// 	getPlanCalcAmountFee(planId,this.formData.bulk).then(res=>{
				// 		this.formData['carriageFee']=res.data
				// 	})	
				// }
			
			},
			//选择包装服务
			changePackingService(){
				this.formData.packingService=='1'?(this.isPackingService=false):(this.isPackingService=true)
			},
			selectGoods(e){
				if(e)
				{
					//节流函数
					let that=this
					if(!that.statu)
					{
						return
					}
					that.statu=false
					setTimeout(()=>{
						this.goodsObject.forEach(item=>{
							if(item.goodsName===e)
							{
								this.formData.goodsType=item.goodsType  //货物类型
								this.formData.packingType=item.packingType  //包装类型
							}
						})
						that.statu=true;
					},1000)
					
				}
			},
			//接收文件传递的id字符串集合
			getFileIdString(fileIds){
				this.formData.otherFiles=fileIds
			},
			//选择计费方式
			selectFeeMode(){
				if(this.formData.feeMode)
				{
					//获取默认计费方式
					this.getNowPricePlanList()
				}
			},
			//获取当前价格计算方案id
			getNowPricePlanList(){
				pricePlanList({}).then(res => {
				    const find = res.rows.find(item => item.feeMode === this.formData.feeMode)
				    if (!find) return
				    this.planId=find.id
				})
			},
			//输入数量
			inputNum(){
				this.calculateCarriageFee(this.planId)
			},
			//输入重量
			inputWeight(){
				this.calculateCarriageFee(this.planId)
			},
			//输入体积
			inputBulk(){
				this.calculateCarriageFee(this.planId)
			},
			//格式化包装费后两位、运费小数点后三位
			limitInput(value, name, num = 2){
				let match = {
				        0: /^\d/g,
				        2: /^\d*(\.?\d{0,2})/g,
				        3: /^\d*(\.?\d{0,3})/g
				      }[num]
				this.$nextTick(() => {
					this.formData[name]=('' + value) // 第一步：转成字符串
						.replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
						.replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
						.replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
						.match(match)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
				})
			},
			//取消保存
			cancelSubmit(){
				uni.navigateBack({
				    delta:1 // 可以不傳delta值，默認為1
				})
			},
			//保存物品信息
			submit(){
				this.$refs.form.validate().then(res=>{
					let pages = getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
					let nowPage = pages[pages.length - 1]; //当前页页面实例
					let prevPage = pages[pages.length - 2]; //上一页页面实例
					
					prevPage.$vm.otherFun(this.formData,this.index)// 給上一頁綁定方法otherFun,傳參formData
					uni.navigateBack({
					    delta:1 // 可以不傳delta值，默認為1
					})
					
				}).catch(err =>{
					uni.showToast({
						title: err[0].errorMessage,
						icon:'none'
					})
				})
			},
		}
	}
</script>

<style scoped>
	::v-deep .file-title{
	    font-size: 12px;
	    color: #333;
	}
	::v-deep .uni-select__input-box{
		width: 0vw;
	}
</style>